import Promise from '../plugins/es6-promise.min';
const systemInfo = wx.getSystemInfoSync();

let domain = "https://weixin.lvacation.cn/";
// const domain = "https://weixin.bunny-club.loc/";
if (systemInfo.platform === 'devtools') {
    domain = "https://weixin.bunny-club.loc/";
}
const param = (obj, traditional) => {
    var params = [];
    params.add = function(k, v) {
        this.push(escape(k) + '=' + encodeURI(v));
    };
    serialize(params, obj);
    return params.join('&').replace(/%20/g, '+');
}

const serialize = (params, obj, traditional, scope) => {

    /**
   *
   * @param obj
   * @returns {boolean}
   */
    function isPlainObject(obj) {
        return typeof obj === 'object' && obj !== null && !(obj !== null && obj === obj.window);
    }

    let type;
    let array = Array.isArray(obj);
    let hash = isPlainObject(obj);
    let that = this;
    if (hash) {
        Object.keys(obj).forEach(function(key) {
            var value = obj[key];
            type = typeof value;
            if (scope) {
                key = traditional
                    ? scope
                    : scope + '[' + (
                        hash || type === 'object' || type === 'array'
                        ? key
                        : '') + ']';
            }
            // handle data in serializeArray() format
            if (!scope && array) {
                serialize(params, value, traditional, key);
                params.add(value.name, value.value);
            } else if (type === 'array' || !traditional && type === 'object') {
                serialize(params, value, traditional, key);
            } else {
                params.add(key, value);
            }
        });
    }
}

const post = (url, data, noLoading) => {
    let originData = data;
    return new Promise((resolve, reject) => {
        if (!noLoading && wx.showLoading) {
            wx.showLoading({title: '努力加载中...'});
        }
        originData.access_token = wx.getStorageSync('WeixinAppThirdSession');
        originData = param(originData, true);
        console.log(url, originData);
        wx.request({
            url: domain + url,
            data: originData,
            method: 'POST',
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            success: function(res) {
                if (res.data.status <= 0) {
                    if (res.data.code === -999) {
                        const app = getApp();
                        app.login((result) => {
                            post(url, data, noLoading).then((res) => {
                                resolve(res);
                            });
                        })
                    } else {
                        wx.showModal({title: '提示', content: res.data.message, showCancel: false});
                        reject(res.data.message);
                    }
                } else {
                    resolve(res.data.data);
                }
            },
            fail: function(error) {
                wx.showModal({title: '', content: JSON.stringify(error)});
                console.log('requestError', error);
                reject(error);
            },
            complete: function(res) {
                if (wx.hideLoading) {
                    wx.hideLoading();
                }
            }
        });
    });

}
export const fetch = {
    post: post,
    domain: domain
}
